#!/bin/bash

# Global variable: Python version list
versions=(
  "3.6.15"
  "3.7.17"
  "3.8.18"
  "3.9.18"
  "3.10.13"
  "3.11.8"
  "3.12.4"
  "3.13.0a4"
)

# Display header
show_header() {
  echo '👉 正在安装 Python 环境...'
  echo '欢迎使用 Python 安装工具'
  echo ''
}

# Check root permissions
check_root() {
  if [ "$(id -u)" = "0" ]; then
    SUDO=""
  else
    SUDO="sudo"
  fi
}

# Install build dependencies
install_dependencies() {
  echo "正在检查并安装必要的构建依赖..."
  if command -v apt-get >/dev/null 2>&1; then
    $SUDO apt-get update
    $SUDO apt-get install -y \
      build-essential \
      zlib1g-dev \
      libncurses5-dev \
      libgdbm-dev \
      libnss3-dev \
      libssl-dev \
      libreadline-dev \
      libffi-dev \
      curl \
      libbz2-dev \
      wget
  elif command -v yum >/dev/null 2>&1; then
    $SUDO yum groupinstall -y "Development Tools"
    $SUDO yum install -y \
      zlib-devel \
      bzip2-devel \
      openssl-devel \
      ncurses-devel \
      gdbm-devel \
      readline-devel \
      libffi-dev \
      curl \
      wget
  else
    echo "❌ 不支持的包管理器，请手动安装依赖。"
    exit 1
  fi
}

# Validate Python version or index
validate_version() {
  local input="$1"
  # Check if input is a number (index)
  if [[ "$input" =~ ^[0-9]+$ ]] && [ "$input" -ge 1 ] && [ "$input" -le "${#versions[@]}" ]; then
    PYTHON_VERSION="${versions[$((input-1))]}"
    return 0
  fi
  # Check if input is a version string
  for version in "${versions[@]}"; do
    if [ "$version" = "$input" ]; then
      PYTHON_VERSION="$input"
      return 0
    fi
  done
  return 1
}

# Main menu for interactive mode
main_menu() {
  while true; do
    clear
    show_header
    echo "请选择操作："
    echo "1. 安装 Python"
    echo "q. 退出"
    
    # Clear input buffer
    while read -r -t 0; do read -r; done
    
    read -r -p "请输入选项 (1/q): " choice
    # echo "调试：main_menu 输入值为 '$choice'" # Uncomment for debugging

    # Trim whitespace and non-printable characters
    choice=$(echo "$choice" | tr -d ' \t\n\r')

    case "$choice" in
      1)
        select_version
        ;;
      q|Q)
        echo "退出程序"
        exit 0
        ;;
      *)
        echo "❌ 输入无效，请重新选择"
        sleep 1
        ;;
    esac
  done
}

# Select Python version for interactive mode
select_version() {
  while true; do
    clear
    show_header
    echo "请选择 Python 版本："
    for i in "${!versions[@]}"; do
      printf "%d. %s\n" "$((i+1))" "${versions[$i]}"
    done

    # Clear input buffer
    while read -r -t 0; do read -r; done
    
    read -r -p "请输入数字（默认 ${versions[-1]}）：" input
    # echo "调试：select_version 输入值为 '$input'" # Uncomment for debugging

    # Trim whitespace and non-printable characters
    input=$(echo "$input" | tr -d ' \t\n\r')

    # Default to the last version if input is empty
    if [ -z "$input" ]; then
      input=${#versions[@]}
    fi

    # Validate input
    if validate_version "$input"; then
      PYTHON_NAME="Python-${PYTHON_VERSION}"
      PYTHON_BIN="python${PYTHON_VERSION:0:3}"
      confirm_install
      return
    else
      echo "❌ 输入无效，请重新选择"
      sleep 1
    fi
  done
}

# Confirm installation for interactive mode
confirm_install() {
  clear
  show_header
  echo "您选择的版本是：$PYTHON_VERSION"
  echo ""
  echo "即将安装 Python $PYTHON_VERSION，确认继续？"
  
  # Clear input buffer
  while read -r -t 0; do read -r; done
  
  read -r -p "输入 y 确认，其他任意键取消: " confirm
  # echo "调试：confirm_install 输入值为 '$confirm'" # Uncomment for debugging

  if [[ "$confirm" =~ ^[Yy]$ ]]; then
    install_python
  else
    echo "已取消安装。"
    sleep 1
  fi
}

# Actual installation process
install_python() {
  show_header
  echo "✅ 开始安装 Python $PYTHON_VERSION..."

  # Install dependencies
  install_dependencies

  # Create temporary directory for installation
  TEMP_DIR=$(mktemp -d)
  cd "$TEMP_DIR" || { echo "❌ 无法创建临时目录"; exit 1; }

  # Download Python source from NPM Mirror (China)
  echo "正在下载 Python $PYTHON_VERSION..."
  wget "https://npmmirror.com/mirrors/python/$PYTHON_VERSION/$PYTHON_NAME.tar.xz" || {
    echo "❌ 下载失败，请检查网络或版本是否正确。"
    cd - >/dev/null
    rm -rf "$TEMP_DIR"
    exit 1
  }

  # Extract tarball
  echo "正在解压 $PYTHON_NAME.tar.xz..."
  tar -xJf "$PYTHON_NAME.tar.xz" || {
    echo "❌ 解压失败。"
    cd - >/dev/null
    rm -rf "$TEMP_DIR"
    exit 1
  }

  cd "$PYTHON_NAME" || { echo "❌ 无法进入目录 $PYTHON_NAME"; exit 1; }

  # Configure, build, and install
  echo "正在配置和编译 Python $PYTHON_VERSION..."
  ./configure --enable-optimizations --with-lto || {
    echo "❌ 配置失败。"
    cd - >/dev/null
    rm -rf "$TEMP_DIR"
    exit 1
  }

  echo "正在编译..."
  make -j$(nproc) || {
    echo "❌ 编译失败。"
    cd - >/dev/null
    rm -rf "$TEMP_DIR"
    exit 1
  }

  echo "正在安装..."
  $SUDO make altinstall || {
    echo "❌ 安装失败。"
    cd - >/dev/null
    rm -rf "$TEMP_DIR"
    exit 1
  }

  # Clean up
  cd - >/dev/null
  rm -rf "$TEMP_DIR"
  echo "✅ Python $PYTHON_VERSION 安装成功！"
  echo "可使用 $PYTHON_BIN --version 检查版本。"
  if [ -t 0 ]; then
    echo "按任意键继续..."
    read -r -n1 -s
  fi
}

# Main logic: Check for non-interactive mode
check_root

# Debug: Log how the script is being called
echo "调试：脚本调用参数：$@, PYTHON_VERSION=$PYTHON_VERSION" >&2

# Check if running interactively or non-interactively
if [ -t 0 ]; then
  # Interactive mode: Show menu
  main_menu
else
  # Non-interactive mode: Use command-line argument, environment variable, or config file
  INPUT_VERSION="${1:-$PYTHON_VERSION}"
  
  # Check for config file if no version specified
  if [ -z "$INPUT_VERSION" ] && [ -f "/tmp/python_version.txt" ]; then
    INPUT_VERSION=$(cat /tmp/python_version.txt | tr -d ' \t\n\r')
  fi

  # Exit if no version specified
  if [ -z "$INPUT_VERSION" ]; then
    echo "❌ 错误：未指定 Python 版本"
    echo "请通过以下方式指定版本："
    echo "1. 命令行参数：./install_python.sh 3.11.8 或 ./install_python.sh 6"
    echo "2. 环境变量：export PYTHON_VERSION=3.11.8"
    echo "3. 配置文件：echo '3.11.8' > /tmp/python_version.txt"
    echo "支持的版本："
    for i in "${!versions[@]}"; do
      printf "%d. %s\n" "$((i+1))" "${versions[$i]}"
    done
    exit 1
  fi

  # Validate version or index
  if validate_version "$INPUT_VERSION"; then
    PYTHON_NAME="Python-${PYTHON_VERSION}"
    PYTHON_BIN="python${PYTHON_VERSION:0:3}"
    install_python
  else
    echo "❌ 无效的 Python 版本或索引：$INPUT_VERSION"
    echo "支持的版本："
    for i in "${!versions[@]}"; do
      printf "%d. %s\n" "$((i+1))" "${versions[$i]}"
    done
    echo "示例：./install_python.sh 3.11.8 或 ./install_python.sh 6"
    exit 1
  fi
fi